package com.imay.photopicker;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.ListPopupWindow;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.imay.capturefilter.R;
import com.imay.capturefilter.camera.CameraEngine;
import com.imay.capturefilter.camera.utils.CameraUtils;
import com.imay.capturefilter.utils.ICCons;
import com.imay.capturefilter.utils.PermissionUtil;
import com.imay.photopicker.activity.BaseActivity;
import com.imay.photopicker.adapter.PopupDirectoryListAdapter;
import com.imay.photopicker.entity.Photo;
import com.imay.photopicker.entity.PhotoDirectory;
import com.imay.photopicker.fragment.CameraFragment;
import com.imay.photopicker.fragment.PhotoPickerFragment;
import com.imay.photopicker.util.MediaStoreHelper;

import java.util.ArrayList;
import java.util.List;

import static com.imay.photopicker.PhotoPicker.EXTRA_PREVIEW_ENABLED;
import static com.imay.photopicker.PhotoPicker.EXTRA_SHOW_CAMERA;
import static com.imay.photopicker.PhotoPicker.EXTRA_SHOW_GIF;

/**
 * Created by Administrator on 2017/3/16.
 */

public class PhotoPickerActivity extends BaseActivity implements PhotoPickerFragment.PhotoItemClickListener,CameraFragment.CameraCallBackListener{

    private PhotoPickerFragment pickerFragment;
    private CameraFragment cameraFragment;

    private int columnNumber = PhotoPickerFragment.DEFAULT_COLUMN_NUMBER;
    private int maxCount;

    //所有photos的路径
    private List<PhotoDirectory> directories;

    private ArrayList<String> originalPhotos;

    private PopupDirectoryListAdapter listAdapter;

    private ListPopupWindow listPopupWindow;


    //目录弹出框的一次最多显示的目录数目
    public static int COUNT_MAX = 8;

    private ImageView mImageView;
    private Context mContext;
    private boolean showCamera;
    private boolean showGif;
    private boolean previewEnabled;
    private int mPosition = 0;
    private List<Photo> photos;

    @Override
    protected int getLayoutId() {
        return R.layout.picker_activity_photo_picker;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        /**
         * 权限控制
         */
        List<String> permissionList = new ArrayList<>();
        if (!PermissionUtil.selfPermissionGranted(this, Manifest.permission.CAMERA)){
            permissionList.add(Manifest.permission.CAMERA);
        }
        if (!PermissionUtil.selfPermissionGranted(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!PermissionUtil.selfPermissionGranted(this, Manifest.permission.READ_EXTERNAL_STORAGE)){
            permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if(!permissionList.isEmpty()){
            String [] permissions = new String[permissionList.size()];
            permissionList.toArray(permissions);
            ActivityCompat.requestPermissions(this,permissions,
                    1);
        }
        
        mContext = this;
        

        showCamera      = getIntent().getBooleanExtra(EXTRA_SHOW_CAMERA, true);
        showGif         = getIntent().getBooleanExtra(EXTRA_SHOW_GIF, false);
        previewEnabled  = getIntent().getBooleanExtra(EXTRA_PREVIEW_ENABLED, true);

        photos = new ArrayList<>();

        setTitle("相机胶卷");
        getTitleBar().getLeftView().getChildAt(0).setScaleX(0.8f);
        getTitleBar().getLeftView().getChildAt(0).setScaleY(0.8f);
        getTitleBar().getLeftView().setPadding(10,0,0,0);
        getTitleBar().setTitleSize(16);

        mImageView = new ImageView(this);
        mImageView.setImageResource(R.mipmap.btn_03photo_up);
        mImageView.setPadding(10,0,10,0);
        getTitleBar().getMiddleView().addView(mImageView,1);

        Bundle mediaStoreArgs = new Bundle();
        mediaStoreArgs.putBoolean(EXTRA_SHOW_GIF, showGif);
        MediaStoreHelper.getPhotoDirs(this, mediaStoreArgs,
                new MediaStoreHelper.PhotosResultCallback() {
                    @Override
                    public void onResultCallback(List<PhotoDirectory> dirs) {
                        directories.clear();
                        directories.addAll(dirs);
                        photos.clear();
                        // 添加相机的ITEM_TYPE
                        photos.addAll(directories.get(mPosition).getPhotos());
                        pickerFragment.setPhotos(photos);
                        notifyDirectories(dirs);
                    }
                });

        pickerFragment = (PhotoPickerFragment) getSupportFragmentManager().findFragmentByTag("tag");
        if (pickerFragment == null) {
            pickerFragment = PhotoPickerFragment
                    .newInstance(showCamera, showGif, previewEnabled, columnNumber, maxCount, originalPhotos);
            pickerFragment.setItemClickListener(this);
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.container, pickerFragment, "tag")
                    .commitAllowingStateLoss();
            getSupportFragmentManager().executePendingTransactions();
        }

        directories = new ArrayList<>();

        listAdapter = new PopupDirectoryListAdapter(directories);

        listPopupWindow = new ListPopupWindow(this);
        listPopupWindow.setWidth(ListPopupWindow.MATCH_PARENT);
        listPopupWindow.setAnchorView(getTitleBar());
        listPopupWindow.setAnimationStyle(R.style.AnimationPreview);
        listPopupWindow.setAdapter(listAdapter);
        listPopupWindow.setModal(true);
        listPopupWindow.setDropDownGravity(Gravity.TOP);
        listPopupWindow.setOnDismissListener(new poponDismissListener());
        listPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 设置点击其他地方 就消失 (只设置这个，没有效果) 必须设置背景
        //listPopupWindow.setOutsideTouchable(true);

        getTitleBar().getMiddleView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listPopupWindow.isShowing()) {
                    listPopupWindow.dismiss();
                } else if (!isFinishing()) {
                    tipDown();

                    adjustHeight();
                    listPopupWindow.show();
                }
            }
        });

        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                listPopupWindow.dismiss();

                PhotoDirectory directory = directories.get(position);

                getTitleBar().setTitle(directory.getName());

                mPosition = position;
                if(pickerFragment != null){
                    List<Photo> photolist = directories.get(position).getPhotos();
                    //pickerFragment.setCurrentDirectoryIndex(position);
                    pickerFragment.setPhotos(photolist);
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 1){
            for(int i = 0; i<permissions.length; i++){
                if(permissions[i].equals(Manifest.permission.CAMERA)){
                    int status = grantResults[i];
                    if(status == 0){
                        /**
                         * 当相机因第一次无法获取权限异常open时返回false信息，进行activty的重启操作
                         */
                        if(!ICCons.cameraOrNull){

                        }
                    }else if(status == -1){
                        Toast.makeText(this,getString(R.string.message_denied), Toast.LENGTH_SHORT).show();
                        finish();
                    }
                    break;
                }
            }
        }
    }

    public void notifyDirectories(List<PhotoDirectory> datas){
        directories.clear();
        directories.addAll(datas);
        listAdapter.notifyDataSetChanged();
        adjustHeight();
    }

    @Override
    public void onItemClick(int position, String path) {
        if(position == 0){
            getTitleBar().setVisibility(View.GONE);

            int flag=WindowManager.LayoutParams.FLAG_FULLSCREEN;
            Window window=getWindow();
            window.addFlags(flag);

            cameraFragment = (CameraFragment) getSupportFragmentManager().findFragmentByTag("camera");
            if(cameraFragment == null){
                cameraFragment = CameraFragment.newInstance();
                getSupportFragmentManager()
                        .beginTransaction()
                        .setTransitionStyle(R.style.FragmentChange)
                        .replace(R.id.container, cameraFragment, "camera")
                        .commitAllowingStateLoss();
                getSupportFragmentManager().executePendingTransactions();
            }
            cameraFragment.setCameraCallBackListener(this);
        }
    }

    @Override
    public void callBack() {
        int flag=WindowManager.LayoutParams.FLAG_FULLSCREEN;
        Window window=getWindow();
        window.clearFlags(flag);

        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.container,pickerFragment)
                .commitAllowingStateLoss();
        getSupportFragmentManager().executePendingTransactions();
        List<Photo> photolist = directories.get(mPosition).getPhotos();
        pickerFragment.setPhotos(photolist);
        getTitleBar().setVisibility(View.VISIBLE);
    }

    class poponDismissListener implements PopupWindow.OnDismissListener{
        @Override
        public void onDismiss() {
            tipUp();
        }
    }

    public void adjustHeight() {
        if (listAdapter == null) return;
        int count = listAdapter.getCount();
        count = count < COUNT_MAX ? count : COUNT_MAX;
        if (listPopupWindow != null) {
            listPopupWindow.setHeight(count * getResources().getDimensionPixelOffset(R.dimen.picker_item_directory_height));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try{
            CameraEngine.startPreview();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        try{
            CameraEngine.stopPreview();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放前后size
        CameraUtils.release();
        CameraEngine.releaseCamera();
        CameraEngine.onDestroy();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        CameraUtils.release();
        CameraEngine.releaseCamera();
        CameraEngine.onDestroy();
    }

    private void tipUp() {
        Animation rotate = AnimationUtils.loadAnimation(mContext, R.anim.tip_up);
        LinearInterpolator lin = new LinearInterpolator();
        rotate.setInterpolator(lin);
        rotate.setFillAfter(true);//动画执行完后是否停留在执行完的状态
        mImageView.setAnimation(rotate);
        mImageView.startAnimation(rotate);

        // 遮罩层消除
        WindowManager.LayoutParams lp=getWindow().getAttributes();
        lp.alpha=1f;
        getWindow().setAttributes(lp);
    }

    private void tipDown() {
        Animation rotate = AnimationUtils.loadAnimation(mContext, R.anim.tip_down);
        LinearInterpolator lin = new LinearInterpolator();
        rotate.setInterpolator(lin);
        rotate.setFillAfter(true);//动画执行完后是否停留在执行完的状态
        mImageView.setAnimation(rotate);
        mImageView.startAnimation(rotate);

        // 遮罩层添加
        WindowManager.LayoutParams lp=getWindow().getAttributes();
        lp.alpha=0.3f;
        getWindow().setAttributes(lp);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == ClipActivity.CLIP_REQUEST_CODE_1 || requestCode == ClipActivity.CLIP_REQUEST_CODE_2){
            if(resultCode == RESULT_OK){
                setResult(RESULT_OK,data);
                finish();
            }
        }
    }
}
